package com.ops.memcache;

import com.ops.memcache.bean.MemCacheBean;
import com.ops.memcache.core.EHCacheManager;
import com.ops.memcache.core.ICache;
import com.ops.memcache.core.ICacheElement;
import com.ops.memcache.utility.EnvironmentConfig;
import com.ops.uitl.common.Common;
import com.ops.uitl.data.DataMap;
import com.ops.uitl.data.DatasetList;
import com.ops.uitl.data.IData;
import com.ops.uitl.data.IDataset;
import com.ops.uitl.tapestry.PageData;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.lang.SystemUtils;
import org.apache.log4j.Logger;

import java.io.*;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.List;
import java.util.Properties;

public class MemCache {
  protected static Logger log = Logger.getLogger(MemCache.class);
  protected static Common common = Common.getInstance();
  public static final String CACHE_NAME = "ECH_MEMCACHE";
  public static final String CHAN_PROPERTIES = "webservice.properties";
  public static final String MEMCACHE_PROPERTIES = "MemCache.properties";
  public static final String CACHE_MODE_DEV = "DEVELOP";
  public static final String CACHE_MODE_PROD = "PRODUCT";

  public MemCache() {
  }

  public static void memcache_Set(IDataset dataset) throws Exception {
    EHCacheManager manager = EHCacheManager.getInstance();
    Iterator iterator = dataset.iterator();

    while(iterator.hasNext()) {
      IData data = (IData)iterator.next();
      manager.putCacheElement("ECH_MEMCACHE", data.getString("KEY"), data.getString("VALUE"));
    }

  }

  public static String memcache_Get(String key) throws Exception {
    EHCacheManager manager = EHCacheManager.getInstance();
    ICache cache = manager.getCache("ECH_MEMCACHE");

    try {
      ICacheElement e = cache.get(key);
      String value = e.getValue().toString() != null && e.getValue().toString().length() > 0?e.getValue().toString():"";
      return value;
    } catch (Exception var5) {
      log.error("[Memcache ERROR]: memcache have exception get key [" + key + "] :  " + var5.getLocalizedMessage());
      if(common.getProperty("ech_MemCache/mode").equals("DEVELOP")) {
        memcache_clean();
        memcache_reload();
      }

      return "";
    }
  }

  public static void memcache_clean() throws Exception {
    EHCacheManager manager = EHCacheManager.getInstance();
    ICache cache = manager.getCache("ECH_MEMCACHE");
    cache.removeAll();
  }

  public static void memcache_reload() throws Exception {
    MemCacheBean bean = new MemCacheBean();
    new DatasetList();
    IDataset dataset = bean.query_MemcacheInfo_bean(new PageData(), new DataMap(), get_chan_id());
    log.error("[Memcache ERROR]: oops ! memcache reload ........");
    memcache_Set(dataset);
  }

  public static IDataset memcache_Print() throws Exception {
    DatasetList caches = new DatasetList();
    EHCacheManager manager = EHCacheManager.getInstance();
    ICache cache = manager.getCache("ECH_MEMCACHE");
    if(cache != null) {
      List list = cache.getKeys();

      for(int i = 0; i < list.size(); ++i) {
        ICacheElement element = cache.get((String)list.get(i));
        if(element != null) {
          Serializable value = element.getValue();
          Serializable name = element.getKey();
          DataMap data = new DataMap();
          data.put("KEY", name == null?"":name);
          data.put("VALUE", value);
          caches.add(data);
        }
      }
    }

    return caches;
  }

  public static void memcache_Stats() throws Exception {
    EHCacheManager manager = EHCacheManager.getInstance();
    ICache cache = manager.getCache("ECH_MEMCACHE");
    log.debug("==========MemCache_Stats===========");
    log.debug("@ HitCount     : " + cache.getHitCount());
    log.debug("@ MissCount    : " + cache.getMissCount());
    log.debug("@ CacheName    : " + cache.getName());
    log.debug("@ CacheSize    : " + cache.getSize());
    log.debug("@ CacheStatus  : " + cache.getStatus());
    log.debug("@ CacheMode    : " + common.getProperty("ech_MemCache/mode"));
    log.debug("===================================");
  }

  public static String get_chan_id() {
    try {
      Properties e = new Properties();
      InputStream fis = MemCache.class.getClassLoader().getResourceAsStream("webservice.properties");
      e.load(fis);
      return e.getProperty("ORGCHANNELID");
    } catch (Exception var2) {
      log.error("[Memcache ERROR]: webservice.properties read error, please check you profile in classes folder.");
      var2.printStackTrace();
      return "";
    }
  }

  public static IDataset memcache_Stats(PageData pd, IData param) throws Exception {
    DatasetList dataset = new DatasetList();
    EHCacheManager mananger = EHCacheManager.getInstance();
    ICache cache = mananger.getCache("ECH_MEMCACHE");
    DataMap data = new DataMap();
    data.put("HitCount", Long.valueOf(cache.getHitCount()));
    data.put("MissCount", Long.valueOf(cache.getMissCount()));
    data.put("CacheName", cache.getName());
    data.put("CacheSize", Integer.valueOf(cache.getSize()));
    data.put("CacheStatus", Integer.valueOf(cache.getStatus()));
    data.put("CacheMode", common.getProperty("ech_MemCache/mode"));
    dataset.add(data);
    return dataset;
  }

  public static Boolean updateCache(String key, String value) throws Exception {
    EHCacheManager mananger = EHCacheManager.getInstance();
    ICache cache = mananger.getCache("ECH_MEMCACHE");

    try {
      cache.put(key, value);
      return Boolean.valueOf(true);
    } catch (Exception var5) {
      var5.printStackTrace();
      return Boolean.valueOf(false);
    }
  }

  public static IDataset getMemCacheProperties() throws Exception {
    DatasetList dataset = new DatasetList();
    Properties props = new Properties();

    try {
      InputStream e = MemCache.class.getClassLoader().getResourceAsStream("MemCache.properties");
      props.load(e);
    } catch (FileNotFoundException var5) {
      var5.printStackTrace();
    } catch (IOException var6) {
      var6.printStackTrace();
    }

    Enumeration e1 = props.keys();

    while(e1.hasMoreElements()) {
      DataMap data = new DataMap();
      String key = (String)e1.nextElement();
      data.put("KEY", key);
      data.put("VALUE", props.getProperty(key));
      dataset.add(data);
    }

    log.error("[Memcache ERROR]: load from MemCache.properties data size:" + dataset.size());
    return dataset;
  }

  public static Boolean setMemCacheProperties(IDataset cacheset, String path) throws Exception {
    if(SystemUtils.IS_OS_WINDOWS) {
      path = path + "WEB-INF\\classes\\" + "MemCache.properties";
    } else {
      path = path + "/WEB-INF/classes/" + "MemCache.properties";
    }

    log.error("MemCache.propertiespath is:" + path);
    Properties prop = new Properties();
    Iterator e = cacheset.iterator();

    while(e.hasNext()) {
      IData data = (IData)e.next();
      prop.setProperty(data.getString("KEY"), data.getString("VALUE"));
    }

    try {
      prop.store(new FileOutputStream(new File(path)), (String)null);
      return Boolean.valueOf(true);
    } catch (Exception var5) {
      var5.printStackTrace();
      return Boolean.valueOf(false);
    }
  }

  public IDataset HttpCall(String url) throws Exception {
    Common common = Common.getInstance();
    Object dataset = new DatasetList();
    new DataMap();

    try {
      HttpClient e = new HttpClient();
      GetMethod getMethod = new GetMethod(url);
      int statusCode = e.executeMethod(getMethod);
      log.debug("response=" + statusCode);
      if(statusCode != 200) {
        log.error("Oops! 出错了: " + getMethod.getStatusLine());
      }

      DataMap data = new DataMap(getMethod.getResponseBodyAsString());
      log.debug("Http Back Data:" + data);
      if(data.getInt("X_RECORDNUM") > 1) {
        dataset = data.toDataset();
      } else {
        ((IDataset)dataset).add(data);
      }

      log.debug("==Action Data==:" + dataset);
      getMethod.releaseConnection();
    } catch (RuntimeException var8) {
      log.error("oops! 出错了: " + var8.getMessage());
      var8.printStackTrace();
    }

    return (IDataset)dataset;
  }

  public static void main(String[] args) {
    EnvironmentConfig ec = EnvironmentConfig.getInstance();
    String driverClassName = ec.getPropertyValue("webservice.properties", "ORGCHANNELID");
    log.debug("driverClassName : " + driverClassName);
  }
}
